<template>
  <div id="login">
    <div class="login-wrap">
      <ul class="menu-tab">
        <li
          :class="{ current: item.current }"
          v-for="item in menuTab"
          :key="item.id"
          @click="toggleMenu(item)"
        >
          {{ item.txt }}
        </li>
      </ul>
      <!-- 表单 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        class="login-form"
        size="medium"
      >
        <el-form-item prop="username" class="item-from">
          <label for="username">邮箱</label>
          <el-input
            type="text"
            id="username"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <label for="password">密码</label>
          <el-input
            type="password"
            id="password"
            v-model="ruleForm.password"
            autocomplete="off"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <!-- 重复密码 -->
        <el-form-item prop="passwords" v-show="model === 'register'">
          <label for="passwords">重复密码</label>
          <el-input
            type="password"
            id="passwords"
            v-model="ruleForm.passwords"
            autocomplete="off"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="code">
          <label for="code">验证码</label>
          <el-row :gutter="10">
            <el-col :span="15"
              ><el-input id="code" v-model="ruleForm.code"></el-input
            ></el-col>
            <el-col :span="9"
              ><el-button
                type="success"
                class="block"
                :disabled="codebuttonStatus.status"
                @click="getSms()"
                >{{ codebuttonStatus.text }}</el-button
              ></el-col
            >
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-button
            type="danger"
            @click="submitForm('loginForm')"
            class="login-btn block"
            :disabled="loginbuttonStatus"
            >{{ model === "login" ? "登陆" : "注册" }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import sha1 from "js-sha1";
import { Message } from "element-ui"; //信息提示
import { GetSms, Register, Login } from "@/api/login.js"; //接口
import {
  stripscript,
  validateEmail,
  validatePass,
  validatecheck,
} from "@/utils/validate"; //信息验证
import { reactive, ref, isRef, toRefs, onMounted } from "@vue/composition-api";
export default {
  // setup(props,context){
  //   console.log(context)
  setup(props, { refs, root }) {
    // 用户名格式
    let validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (validateEmail(value)) {
        callback(new Error("用户名格式有误"));
      } else {
        callback(); //true
        // console.log(true)
      }
    };
    //   验证密码
    let validatePassword = (rule, value, callback) => {
      ruleForm.password = stripscript(value);
      value = ruleForm.password;
      console.log(value);
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (validatePass(value)) {
        callback(new Error("密码为6至20位数字+字母!"));
      } else {
        callback();
        // console.log(true)
      }
    };
    //二次密码验证
    let validatePasswords = (rule, value, callback) => {
      //如果模块type为login的时候直接通过
      if (model.value === "login") {
        callback();
      }
      ruleForm.passwords = stripscript(value);
      value = ruleForm.passwords;
      console.log(value);

      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value != ruleForm.password) {
        callback(new Error("重复密码不正确!"));
      } else {
        callback();
        // console.log(true)
      }
    };
    //   验证码格式
    let validateCode = (rule, value, callback) => {
      ruleForm.code = stripscript(value);
      value = ruleForm.code;
      console.log(value);
      if (value === "") {
        return callback(new Error("验证码不能为空"));
      } else if (validatecheck(value)) {
        return callback(new Error("验证码格式错误"));
      } else {
        callback();
        // console.log(true)
      }
    };
    /**
     * 声明数据
     */
    //放data数据,生命周期,自定义函数
    //reactive声明一个单一对象的时候时使用

    //menuTab的登陆与注册状态的绑定
    const menuTab = reactive([
      { txt: "登录", current: true, type: "login" },
      { txt: "注册", current: false, type: "register" },
    ]);
    const model = ref("login");

    //声明一个计时器
    const timer = ref(null);

    // const codebuttonStatus = ref(false)
    // const codebuttonText = ref('获取验证码')
    const codebuttonStatus = reactive({
      status: false,
      text: "获取验证码",
    });

    //login开关的使用:
    const loginbuttonStatus = ref(true);

    // console.log(model.value)
    // 表单数据绑定:
    const ruleForm = reactive({
      username: "",
      password: "",
      code: "",
      passwords: "",
    });
    //表单的验证规则:
    const rules = reactive({
      username: [{ validator: validateUsername, trigger: "blur" }],
      password: [{ validator: validatePassword, trigger: "blur" }],
      passwords: [{ validator: validatePasswords, trigger: "blur" }],
      code: [{ validator: validateCode, trigger: "blur" }],
    });

    /**
     * 声明方法函数
     * 需要return出去
     * 不用this
     */

    // 登陆状态与注册状态的切换
    const toggleMenu = (data) => {
      // 遍历menuTab排他
      menuTab.forEach((elem) => {
        elem.current = false;
      });
      // 使当前对应的data.current状态切换成true, item.current = true  :class="{current:item.current}"
      data.current = true;
      //修改model的值
      model.value = data.type;
      // 重置表单
      resetFormData();
      // 清除定时器
      clearCountDown();
    };

    /**
     * 重置表单
     */
    const resetFormData = () => {
      // this.$refs[formName].resetFields();//2.0的写法
      refs.loginForm.resetFields(); //3.0的写法.
    };

    /**
     * 更新按钮的状态
     */
    const updatecodebuttonStatus = (params) => {
      codebuttonStatus.status = params.status;
      codebuttonStatus.text = params.text;
    };

    /**
     * 获取验证码
     */
    /**
     * 提交表单
     */
    const getSms = () => {
      // 邮箱非空验证
      if (ruleForm.username === "") {
        // 进行提示接口请求
        //空值的时候时的错误提示
        root.$message({
          showClose: true,
          message: "用户名不能为空",
          type: "error",
        });
        //返回 false不再执行下一步
        return false;
      }
      //邮箱格式验证
      if (validateEmail(ruleForm.username)) {
        // 错误提示
        root.$message.error("邮箱有误请重新输入");
        //返回 false不再执行下一步
        return false;
      }
      // 请求接口

      //设置请求时候的数据
      let requestData = {
        username: ruleForm.username,
        module: model.value,
      };

      // codebuttonStatus.status = true
      // codebuttonStatus.text = '发送中'
      updatecodebuttonStatus({
        status: true,
        text: "发送中",
      });
      setTimeout(() => {
        GetSms(requestData)
          .then((response) => {
            let data = response.data;
            root.$message({
              showClose: true,
              message: data.message,
              type: "success",
            });
            //启动登录或者注册按钮
            loginbuttonStatus.value = false;
            countDown(0);
          })
          .catch((error) => {
            console.log(error);
          });
      }, 0);
      // alert("asdasd")
    };

    // 提交表单
    const submitForm = (formName) => {
      refs[formName].validate((valid) => {
        console.log("1111", valid);
        //表单验证通过
        if (valid) {
          model.value === "login" ? login() : register();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };
    /**
     * 注册方法
     */
    const register = () => {
      // alert('submit!');
      let requestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password),
        code: ruleForm.code,
        module: model.value,
      };
      Register(requestData)
        .then((response) => {
          let data = response.data;
          root.$message({
            showClose: true,
            message: data.message,
            type: "success",
          });
          console.log(response);
          toggleMenu(menuTab[0]);
          clearCountDown();
        })
        .catch((error) => {});
    };

    /**
     * 登陆方法
     */

    const login = () => {
      let requestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password),
        code: ruleForm.code,
        module: model.value,
      };

      root.$store
        .dispatch("app/login", requestData)
        .then((response) => {
          console.log(response);
          root.$router.push({
            path: "/console",
          });
        })
        .catch((error) => {
          console.log(error);
        });
      // Login(requestData).then(response=>{
      //     console.log('登陆成功')
      //     console.log(response)
      //     //页面跳转

      //   }).catch(error=>{
      //   console.log(error)
      //   })
    };

    /**
     * 倒计时
     */
    const countDown = (number) => {
      //判断定时器是否已经存在,存在就清除
      if (timer.value) {
        clearInterval(timer.value);
      }
      //60秒和0秒的时候不见了 故意留BUG
      // 存储定时器
      let time = number;
      console.log(time);
      timer.value = setInterval(() => {
        time--;
        if (time === 0) {
          clearInterval(timer.value);
          //   codebuttonStatus.status = false
          // codebuttonStatus.text = '再次发送'
          updatecodebuttonStatus({
            status: false,
            text: "再次发送",
          });
        } else {
          codebuttonStatus.text = `倒计时${time}秒`;
        }
      }, 1000);
    };

    /**
     * 清除倒计时
     */

    const clearCountDown = () => {
      // 切换登陆的时候还原验证码状态
      // codebuttonStatus.status = false
      // codebuttonStatus.text = '获取验证码'
      updatecodebuttonStatus({
        status: false,
        text: "获取验证码",
      });
      // 清除倒计时
      clearInterval(timer.value);

      // const codebuttonStatus = reactive({
      //     status:false,
      //     text:'获取验证码'
      // })
    };

    // 生命周期3.0
    onMounted(() => {});
    return {
      menuTab,
      model,
      toggleMenu,
      submitForm,
      ruleForm,
      rules,
      getSms,
      loginbuttonStatus,
      codebuttonStatus,
      timer,
      clearCountDown,
      login,
      register,
    };
  },
  name: "login",
};
</script>
<style lang="scss" scoped>
#login {
  height: 100vh;
  background-color: #344a5f;
}
.login-wrap {
  width: 330px;
  margin: auto;
}
.menu-tab {
  text-align: center;
  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }
  .current {
    background-color: rgba(0, 0, 0, 0.1);
  }
}
.login-form {
  margin-top: 29px;
  label {
    display: block;
    font-size: 14px;
    color: #fff;
    margin-bottom: 3px;
  }
  .item-from {
    margin-bottom: 13px;
  }
  .block {
    width: 100%;
    display: block;
  }
  .login-btn {
    margin-top: 19px;
  }
}
</style>